﻿using Lee.Models.Entities;
using Lee.Utility.Config;
using Lee.Utility.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;

namespace Lee.EF.Context
{
    public class MyDBContext : DbContext
    {
        private string _connectionString = GlobalConfig.SystemConfig.DBConnectionString;
        public string myguid { get; set; }

        public MyDBContext()
        {
            myguid = "MyDBContext" + Guid.NewGuid().ToString();
        }

        public MyDBContext(DbContextOptions<MyDBContext> options) : base(options)//options: GeContexttOptions(options)
        {
            myguid = Guid.NewGuid().ToString();
            ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
            ChangeTracker.StateChanged += UpdateEntityOnChanged;
            ChangeTracker.Tracked += UpdateEntityOnChanged;
        }

        public DbSet<Biz_Coupons> Biz_Coupons { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //optionsBuilder.UseLazyLoadingProxies();//启用懒加载
            if (!optionsBuilder.IsConfigured)
            {
                //if (string.IsNullOrEmpty(_connectionString))
                //    _connectionString = "Server=localhost;Database=DH;User Id=sa;Password=2021@ldh;";
                //optionsBuilder.UseSqlServer(_connectionString);

                _connectionString = "server=127.0.0.1;uid=root;pwd=123456;port=3306;database=ldh;Allow User Variables=True;sslMode=None";

                //_connectionString = "server=sh-cynosdbmysql-grp-brbuc2xq.sql.tencentcdb.com;userid=root;pwd=***;port=21952;database=ldh;Convert Zero Datetime=True;Allow User Variables=True;sslMode=None";
                optionsBuilder.UseMySql(_connectionString, ServerVersion.Create(8, 0, 22, ServerType.MySql), builder =>
                {
                    builder.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 });
                });

                //var serverVersion = new MariaDbServerVersion(new Version("8, 0, 22"));
                //optionsBuilder.UseMySql(_connectionString, serverVersion, optionsBuilder =>
                //{
                //    optionsBuilder.MinBatchSize(4);
                //    optionsBuilder.CommandTimeout(10);
                //    //optionsBuilder.MigrationsAssembly(mysqlConfig.MigrationAssembly);
                //    optionsBuilder.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
                //}).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
            }
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyDBContext).Assembly);

            base.OnModelCreating(modelBuilder);
        }

        private static void UpdateEntityOnChanged(object? sender, EntityEntryEventArgs e)
        {
            if (e.Entry.Entity is BaseEntity<int> entityopt)
            {
                switch (e.Entry.State)
                {
                    case EntityState.Deleted:
                        entityopt.isdeleted = true;
                        entityopt.update_time = DateTime.Now;
                        entityopt.update_by = "system";
                        break;

                    case EntityState.Modified:
                        entityopt.update_time = DateTime.Now;
                        entityopt.update_by = "system";
                        break;

                    case EntityState.Added:
                        entityopt.isdeleted = false;
                        entityopt.create_time = DateTime.Now;
                        entityopt.create_by = "system";
                        break;
                }
            }
        }
    }
}